﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using X.Json;
using X.Json.Linq;


namespace geetol.sms.core
{
    public class Serialize
    {
        public static string ToJson(object o) { return ToJson(o, false); }
        public static string ToJson(object o, bool ignore)
        {
            if (o == null) return "";
            var jss = new JsonSerializerSettings();
            if (ignore) jss.NullValueHandling = NullValueHandling.Ignore;
            jss.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            jss.DateFormatHandling = DateFormatHandling.IsoDateFormat;
            return JsonConvert.SerializeObject(o, jss);
        }

        public static T FromJson<T>(string json)
        {
            if (string.IsNullOrEmpty(json)) return default(T);
            var jss = new JsonSerializerSettings();
            jss.NullValueHandling = NullValueHandling.Ignore;
            jss.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            jss.DateFormatHandling = DateFormatHandling.IsoDateFormat;
            return JsonConvert.DeserializeObject<T>(json, jss);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="json"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static Dictionary<string, string> JsonToDict(string json)
        {
            var dict = new Dictionary<string, string>();
            if (string.IsNullOrEmpty(json)) return dict;

            var jo = JObject.Parse(json);
            var n = jo.GetEnumerator();
            while (n.MoveNext())
            {
                dict.Add(n.Current.Key, n.Current.Value.ToString());
            }
            return dict;
        }

    }
}
